<template>
	<scroll-view style="height: 100%;" scroll-y="true">
		<view class="form-content" style="margin: 0px 15px;">
			<view class="content-title">
				<view>中国人民政治协商会议</view>
				<view>澄迈县第{{userInfo.jieci}}届委员会第{{userInfo.huiyi}}次会议提案</view>
				<image src="https://zhzx.on-line-demo.com/image/line.png" mode="widthFix"
					style="width: 100%;margin-top: 10px;"></image>
			</view>
			<uni-forms :labelWidth="90" :modelValue="formData">
				<uni-forms-item label="提案方式">
					<radio-group @change="radioChange" class="radio-group">
						<label class="radio" v-for="(item, index) in items" :key="item.value">
							<radio :value="item.value" :checked="formData.method == item.value" />{{item.name}}
						</label>
					</radio-group>
				</uni-forms-item>
				<uni-forms-item label="案由" required>
					<uni-easyinput type="textarea" maxlength="-1" autoHeight v-model="formData.title" placeholder="请输入"
						:placeholderStyle="placeholderStyle" />
				</uni-forms-item>
				<uni-forms-item label="提案人" v-if="formData.method != 3">
					<view class="text">{{userInfo.nickname}}</view>
				</uni-forms-item>
				<uni-forms-item label="提案单位" v-if="formData.method == 3">
					<uni-easyinput type="textarea" maxlength="-1" autoHeight v-model="formData.proposer"
						placeholder="请输入" :placeholderStyle="placeholderStyle" />
				</uni-forms-item>
				<picker class="picker" @change="(res) => bindPickerChange(res, 'circles')" :value="circlesIdx"
					:range="circlesList" range-key="name">
					<uni-forms-item :label="formData.method != 3 ? '界别' : '领衔人界别'">
						<view class="input-arrow">
							<view class="uni-input">{{circlesList[circlesIdx] && circlesList[circlesIdx].name}}</view>

							<uni-icons type="forward" size="20" class="arrow"></uni-icons>
						</view>
					</uni-forms-item>
				</picker>
				<!-- <uni-forms-item label="领衔人界别" v-if="formData.method == 3">
					<view class="input-arrow">
						<picker class="picker" @change="(res) => bindPickerChange(res, 'circles')" :value="circlesIdx"
							:range="circlesList" range-key="name">
							<view class="uni-input">{{circlesList[circlesIdx] && circlesList[circlesIdx].name}}</view>
						</picker>
						<uni-icons type="forward" size="20" class="arrow"></uni-icons>
					</view>
				</uni-forms-item> -->
				<picker class="picker" @change="(res) => bindPickerChange(res, 'party')" :value="partyIdx"
					:range="partyList" range-key="name">
					<uni-forms-item :label="formData.method != 3 ? '党派' : '领衔人党派'">
						<view class="input-arrow">
							<view class="uni-input">{{partyList[partyIdx] && partyList[partyIdx].name}}</view>

							<uni-icons type="forward" size="20" class="arrow"></uni-icons>
						</view>
					</uni-forms-item>
				</picker>
				<!-- <uni-forms-item label="领衔人党派" v-if="formData.method == 3">
					<view class="input-arrow">
						<picker class="picker" @change="(res) => bindPickerChange(res, 'party')" :value="partyIdx" :range="partyList" range-key="name">
							<view class="uni-input">{{partyList[partyIdx] && partyList[partyIdx].name}}</view>
						</picker>
						<uni-icons type="forward" size="20" class="arrow"></uni-icons>
					</view>
				</uni-forms-item> -->
				<picker class="picker" @change="(res) => bindPickerChange(res, 'caseType')" :value="caseTypeIdx"
					:range="casetypeList" range-key="name">
					<uni-forms-item label="提案归类">
						<view class="input-arrow">
							<view class="uni-input" v-if="casetypeList[caseTypeIdx] && casetypeList[caseTypeIdx].name">
								{{casetypeList[caseTypeIdx] && casetypeList[caseTypeIdx].name}}
							</view>
							<uni-easyinput type="text" v-else :clearable="false" placeholder="请选择" />
							<uni-icons type="forward" size="20" class="arrow"></uni-icons>
						</view>
					</uni-forms-item>
				</picker>
				<uni-forms-item label="附议人" v-if="formData.method != 3">
					<view class="input-arrow" @click.stop="showPopup('user')">
						<uni-easyinput type="textarea" maxlength="-1" autoHeight :clearable="false" v-model="userText"
							placeholder="请选择" :placeholderStyle="placeholderStyle" />
						<uni-icons type="forward" size="20" class="arrow"></uni-icons>
					</view>
				</uni-forms-item>
				<uni-forms-item label="领衔人" v-if="formData.method == 3">
					<view class="text">{{userInfo.nickname}}</view>
				</uni-forms-item>
				<uni-forms-item label="执笔人" v-if="formData.method == 3">
					<view class="input-arrow" @click.stop="showPopup('writer')">
						<uni-easyinput type="text" :clearable="false" v-model="writerText" placeholder="请选择" />
						<uni-icons type="forward" size="20" class="arrow"></uni-icons>
					</view>
				</uni-forms-item>
				<uni-forms-item label="提案组成员" v-if="formData.method == 3">
					<view class="input-arrow" @click.stop="showPopup('group')">
						<uni-easyinput type="textarea" maxlength="-1" autoHeight :clearable="false" v-model="groupText"
							placeholder="请选择" :placeholderStyle="placeholderStyle" />
						<uni-icons type="forward" size="20" class="arrow"></uni-icons>
					</view>
				</uni-forms-item>
				<uni-forms-item :label="formData.method != 3 ? '提案人电话' : '领衔人电话'">
					<uni-easyinput type="text" :clearable="false" v-model="formData.mobile" placeholder="请输入" />
				</uni-forms-item>
				<uni-forms-item label="通讯地址">
					<uni-easyinput type="textarea" maxlength="-1" autoHeight v-model="formData.address"
						placeholder="请输入" :placeholderStyle="placeholderStyle" />
				</uni-forms-item>
				<uni-forms-item label="提案内容" required>
					<!-- <uni-easyinput type="textarea" maxlength="-1" autoHeight v-model="formData.content" placeholder="请输入"
						:placeholderStyle="placeholderStyle" /> -->
				</uni-forms-item>
				<sp-editor :toolbar-config="{
				          excludeKeys: ['direction', 'date', 'lineHeight', 'letterSpacing', 'listCheck'],
				          iconSize: '18px'
				        }" @init="initEditor" @input="inputOver" @upinImage="upinImage"></sp-editor>
				<!-- <uni-forms-item label="建议办法" required>
					<uni-easyinput type="textarea" maxlength="-1" autoHeight v-model="formData.propose" placeholder="请输入"
						:placeholderStyle="placeholderStyle" />
				</uni-forms-item> -->
			</uni-forms>
			<button type="primary" class="btn submit" @click="submitForm(1)">正式提交</button>
			<button type="primary" class="btn save" @click="submitForm(2)">保存草稿</button>
			<button type="primary" class="btn delete" @click="deleteProposal()" v-if="id">删除草稿</button>
		</view>
		<view class="bottom-popup" v-show="showUser">
			<view class="mask" @click="showUser=false"></view>
			<view class="popup">
				<view class="btns">
					<span class="cacle" @click="showUser=false">取消</span>
					<span class="sure" @click="sureUser">完成</span>
				</view>
				<view class="list-content">
					<uni-search-bar @confirm="search" v-model="keywords" clearButton="auto" cancelButton="none"
						placeholder="请输入姓名进行搜索" class="search-bar"></uni-search-bar>
					<scroll-view scroll-y="true" class="list">
						<view v-for="item in userData" :key="item.id" class="list-item" @click.stop="userClick(item)">
							<span>{{item.nickname}}</span>
							<span>
								<radio :checked="checked.indexOf(item.id) != -1" @click.stop="userClick(item)" />
							</span>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>
	</scroll-view>
</template>

<script>
	import request from '../../common/request'
	import upload from '../../common/upload.js'
	export default {
		props: ['id'],
		components: {

		},
		data() {
			return {
				formData: {
					method: 1,
					case_type: '',
					circles: '',
					party: '',
					proposer: '',
					user_ids: '',
					writer: '',
					mobile: '',
					address: '',
					title: '',
					content: '',
					propose: '',
					draft: '',
				},
				items: [{
					value: '1',
					name: '委员提案'
				}, {
					value: '3',
					name: '集体提案'
				}],
				userData: [],
				circlesList: [],
				circlesIdx: '0',
				partyList: [],
				partyIdx: '0',
				casetypeList: [],
				caseTypeIdx: '',
				page: 1,
				loadStatus: 'loading',
				showLoad: false,
				keywords: '',
				showUser: false,
				checked: [],
				userChecked: [],
				userText: '',
				groupChecked: [],
				groupText: '',
				checkedType: '',
				writerChecked: [],
				writerText: '',
				userInfo: {},
				placeholderStyle: 'paddingTop:5px;font-size: 14px',
				editorIns: null
			}
		},
		onLoad() {
		},
		mounted() {
			if (this.id) {
				Promise.all([this.getUserInfo(), this.getDetailData(), this.getDataList(), this.getUserProposal()]).then(
					data => {
						this.circlesList.forEach((item, index) => {
							if (item.id == this.formData.circles) this.circlesIdx = index
						})
						this.partyList.forEach((item, index) => {
							if (item.id == this.formData.party) this.partyIdx = index
						})
						this.casetypeList.forEach((item, index) => {
							if (item.id == this.formData.case_type) this.caseTypeIdx = index
						})

					})
			} else {
				Promise.all([this.getUserInfo(), this.getDataList(), this.getUserProposal()]).then(data => {
					this.circlesList.forEach((item, index) => {
						if (item.id == this.userInfo.circles) this.circlesIdx = index
					})
					this.partyList.forEach((item, index) => {
						if (item.id == this.userInfo.party) this.partyIdx = index
					})

					this.formData.mobile = this.userInfo.mobile
					this.formData.address = this.userInfo.address
				})
			}
		},
		methods: {
			/**
			 * 获取输入内容
			 * @param {Object} e {html,text} 内容的html文本，和text文本
			 */
			inputOver(e) {
				// 可以在此处获取到编辑器已编辑的内容
				// console.log('==== inputOver :', e)
				this.formData.content = e.html
			},
			/**
			 * 编辑器就绪
			 * @param {Object} editor 编辑器实例，你可以自定义调用editor实例的方法
			 * @tutorial editor组件 https://uniapp.dcloud.net.cn/component/editor.html#editor-%E7%BB%84%E4%BB%B6
			 * @tutorial 相关api https://uniapp.dcloud.net.cn/api/media/editor-context.html
			 */
			initEditor(editor) {
				console.log(editor)
				this.editorIns = editor // 保存编辑器实例
				// 保存编辑器实例后，可以在此处获取后端数据，并赋值给编辑器初始化内容
				this.preRender()
			},
			preRender(html) {
				setTimeout(() => {
					// 异步获取后端数据后，初始化编辑器内容
					this.editorIns.setContents({
						html: html
					})
				}, 1000)
			},
			/**
			 * 以$emit('upinImage', tempFiles, this.editorCtx)的方式回调
			 * @param {Object} tempFiles
			 * @param {Object} editorCtx
			 */
			upinImage(tempFiles, editorCtx) {
				tempFiles.forEach(async (item) => {
					upload({
						url:'/common/upload',
						file: item.tempFilePath
					}).then(res => {
						res = JSON.parse(res)
						if(res.code == 1){
							editorCtx.insertImage({
								src: res.data.fullurl,
								width: '80%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
								success: function() {
									// uni.hideLoading()
								}
							})
						}else{
							uni.showToast({
								title: '图片上传失败',
								icon: 'none',
								duration: 2000
							});
						}
					})
				})

			},
			getUserInfo() {
				return new Promise(resolve => {
					request({
						url: '/user/userInfo',
						method: 'POST',
					}).then(res => {
						if (res.code == 1) {
							this.userInfo = res.data
							resolve()
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 2000
							});
						}
					})
				})

			},
			getDetailData() {
				return new Promise(resolve => {
					request({
						url: '/proposal/detail',
						data: {
							proposal_id: this.id
						},
						method: 'POST'
					}).then(res => {
						if (res.code == 1) {
							this.formData = res.data
							this.preRender(res.data.content)
							if (this.formData.method == 2) this.formData.method = 1
							let text = res.data.user_ids_text.split(','),
								ids = res.data.user_ids.split(',')
							if (res.data.method != 3) {
								this.userText = res.data.user_ids_text
								ids.forEach((id, index) => {
									this.userChecked.push({
										id: Number(id),
										nickname: text[index]
									})
								})
							} else {
								this.groupText = res.data.user_ids_text
								ids.forEach((id, index) => {
									this.groupChecked.push({
										id: Number(id),
										nickname: text[index]
									})
								})
							}
							this.writerText = res.data.writer_text
							this.writerChecked = [{
								id: Number(res.data.writer),
								nickname: res.data.writer_text
							}]
							resolve()
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 2000
							});
						}
					})
				})

			},
			search(res) {
				this.getUserProposal()
			},
			showPopup(type) {
				this.getUserProposal()
				this.checkedType = type
				this.checked = []
				if (type == 'user') {
					this.userChecked.forEach(item => this.checked.push(item.id))
				} else if (type == 'group') {
					this.groupChecked.forEach(item => this.checked.push(item.id))
				} else {
					this.writerChecked.forEach(item => this.checked.push(item.id))
				}
				this.showUser = true
			},
			userClick(data) {
				let idx = this.checked.indexOf(data.id)
				if (idx == -1) {
					this.checked.push(data.id)
					if (this.checkedType == 'user') {
						this.userChecked.push(data)
					} else if (this.checkedType == 'group') {
						this.groupChecked.push(data)
					} else {
						this.checked = [data.id]
						this.writerChecked = [data]
					}
				} else {
					this.checked.splice(idx, 1)
					if (this.checkedType == 'user') {
						this.userChecked.splice(idx, 1)
					} else if (this.checkedType == 'group') {
						this.groupChecked.splice(idx, 1)
					} else {
						this.writerChecked.splice(idx, 1)
					}
				}
			},
			sureUser() {
				let names = []
				if (this.checkedType == 'user') {
					this.userChecked.forEach(item => names.push(item.nickname))
					this.userText = names.join('，')
				} else if (this.checkedType == 'group') {
					this.groupChecked.forEach(item => names.push(item.nickname))
					this.groupText = names.join('，')
				} else {
					this.writerChecked.forEach(item => names.push(item.nickname))
					this.writerText = names.join('，')
				}
				this.showUser = false
			},
			bindPickerChange(e, type) {
				switch (type) {
					case 'circles':
						this.circlesIdx = e.detail.value
						break;
					case 'party':
						this.partyIdx = e.detail.value
						break;
					case 'caseType':
						this.caseTypeIdx = e.detail.value
						break;
					case 'user':
						this.userIdx = e.detail.value
						break;
				}
			},
			radioChange(res) {
				this.formData.method = res.detail.value
			},
			lowerBottom() {
				if (this.loadStatus != 'loading') {
					this.loadStatus = 'loading'
					this.showLoad = true
					this.page++
					this.getUserProposal()
				}
			},
			getUserProposal() {
				return new Promise(resolve => {
					request({
						url: '/proposal/userProposal',
						data: {
							page: this.page,
							keywords: this.keywords
						},
						method: 'POST',
					}).then(res => {
						if (res.code == 1) {
							this.userData = res.data
							if (this.page == res.lastPage) {
								this.loadStatus = 'no-more'
							} else {
								this.loadStatus = 'more'
								this.showLoad = false
							}
							resolve()
						} else {
							this.loadStatus = 'no-more'
						}
					})
				})

			},
			getDataList() {
				return new Promise(resolve => {
					request({
						url: '/proposal/dataList',
						method: 'POST',
					}).then(res => {
						if (res.code == 1) {
							this.circlesList = res.data[0] && res.data[0].circlesList
							this.partyList = res.data[0] && res.data[0].partyList
							this.casetypeList = res.data[0] && res.data[0].casetypeList
							resolve()
						}
					})
				})
			},
			submitForm(type) {
				let param = {
					method: this.formData.method,
					case_type: this.casetypeList[this.caseTypeIdx] && this.casetypeList[this.caseTypeIdx].id || '',
					circles: this.circlesList[this.circlesIdx] && this.circlesList[this.circlesIdx].id,
					party: this.partyList[this.partyIdx] && this.partyList[this.partyIdx].id,
					proposer: this.formData.proposer,
					user_ids: '',
					writer: '',
					mobile: this.formData.mobile,
					address: this.formData.address,
					title: this.formData.title,
					content: this.formData.content,
					propose: this.formData.propose,
					draft: type,
				}
				let ids = []
				if (this.formData.method == 3) {
					this.groupChecked.forEach(item => ids.push(item.id))
					param.writer = this.writerChecked[0] && this.writerChecked[0].id || ''
				} else {
					this.userChecked.forEach(item => ids.push(item.id))
				}
				param.user_ids = ids.join(',')
				if (this.id) {
					param.proposal_id = this.id
					request({
						url: '/proposal/editProposal',
						data: param,
						method: 'POST',
					}).then(res => {
						if (res.code == 1) {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 2000
							});
							this.timeout = setTimeout(() => {
								let data = {
									page: 'form',
									type: type
								}
								uni.$emit('showContent', data)
							}, 2000)
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 2000
							});
						}
					})
				} else {
					request({
						url: '/proposal/addProposal',
						data: param,
						method: 'POST',
					}).then(res => {
						if (res.code == 1) {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 2000
							});
							this.timeout = setTimeout(() => {
								let data = {
									page: 'form',
									type: type
								}
								uni.$emit('showContent', data)
							}, 2000)
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 2000
							});
						}
					})
				}
			},
			deleteProposal() {
				request({
					url: '/proposal/delDraft',
					data: {
						proposal_id: this.id
					},
					method: 'POST'
				}).then(res => {
					if (res.code == 1) {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						});
						this.timeout = setTimeout(() => {
							let data = {
								page: 'form',
								type: 2
							}
							uni.$emit('showContent', data)
						}, 2000)
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						});
					}
				})
			},
		}

	}
</script>

<style>
	.text {
		line-height: 36px;
		padding-left: 10px;
	}

	.bottom-popup {
		position: fixed;
		top: 0px;
		left: 0px;
		width: 100%;
		height: 100%;
		z-index: 999;
	}

	.bottom-popup .mask {
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
	}

	.bottom-popup .popup {
		background-color: #fff;
		position: absolute;
		bottom: 0px;
		left: 0px;
		width: 100%;
		height: 50%;
	}

	.btns {
		display: flex;
		align-items: center;
		justify-content: space-between;
		border: 1px solid #efefef;
	}

	.btns span,
	.btns label {
		padding: 0px 14px;
		font-size: 17px;
		line-height: 45px;
	}

	.btns .cacle {
		color: #888;
	}

	.btns .sure {
		color: #2668be;
	}

	.bottom-popup .list-content {
		height: calc(100% - 45px)
	}

	.bottom-popup .list {
		height: calc(100% - 60px);
	}

	.bottom-popup .list-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 8px 10px;
	}

	.bottom-popup .list-item:not(:first-child) {
		border-top: 1px solid #efefef;
	}

	.content-title {
		font-size: 18px;
		text-align: center;
		margin-bottom: 15px;
		font-weight: 600;
		line-height: 28px;
	}

	.form-content {
		padding: 30px 0px 20px;
	}

	.radio-group {
		line-height: 35px;


	}

	.radio-group .radio {
		margin-right: 20px;
	}

	.input-arrow {
		display: flex;
		align-items: center;
		justify-content: space-between;


	}

	.input-arrow .uni-input {
		padding-left: 10px;
		width: calc(100% - 10px);
		height: 36px;
		line-height: 36px;
	}

	.input-arrow .arrow {
		color: rgb(187, 187, 187) !important;
	}

	.btn {
		margin-bottom: 15px;
		font-size: 14px;
		padding: 5px;
		border-radius: 30px;
	}

	.btn.submit {
		background-color: #2668be;
		margin-top: 50px;
	}

	.btn.save {
		background-color: #fb7a30;
	}

	.btn.delete {
		background-color: #ea5c55;
	}
</style>